var express = require('express');
var router = express.Router();
var cartDAO = require("../bin/db/cartDAO.js");
// 添加购物车接口
router.post("/chartadd",(req,res)=>{
    cartDAO.findOne({goods:req.body.goods,reg:req.body.reg,users:req.body.users})
    .then(data=>{
        if(data){
            data.gnum = data.gnum*1+req.body.gnum*1;
            data.save();
            res.json({err:0,msg:"加入购物车成功"});
        }else{
            var c = new cartDAO(req.body);
            c.save()
            .then(data=>{
                res.json({err:0,msg:"加入购物车成功"});
            });
        }
    });
    
});


router.post("/findchart",(req,res)=>{
    cartDAO.find({users:req.body._id})
    .populate("goods")
    .then(data=>{
        
        res.json({err:0,data:data});
    });
});

router.post("/editchart",(req,res)=>{
    var currentObj = {};
    if(req.body.gnum){
        currentObj.gnum = req.body.gnum;
    }
    if(req.body.reg){
        currentObj.reg = req.body.reg;
    }
    cartDAO.update({_id:req.body._id},{
        $set:currentObj
    })
    .then(data=>{
         cartDAO.findOne({_id:req.body._id})
         .then(d=>{
             cartDAO.find({goods:d.goods,users:d.users,reg:d.reg})
            .then(da=>{
                             var n = 0;
                if(da.length>1){
                    for(var i = 0;i<da.length;i++){;
                        if(da[i]._id!=req.body._id){
                            n = n*1 +da[i].gnum*1;
                            cartDAO.remove({_id:da[i]._id})
                            .then(()=>{  
                            });
                        }
                    }
                }
                    d.gnum=d.gnum*1+n*1;
                    d.save();
                    res.json({err:0,msg:"商品数据修改成功"});
            });
            
         })
        
    });
});

router.post("/deletechart",(req,res)=>{
    var arr = req.body.inputId;
    var parr = [];
    for (var i = 0; i < arr.length; i++) {
        parr.push(cartDAO.remove({_id:arr[i]}));
    }
    Promise.all(parr)
    .then(data=>{
        res.json({err:0,msg:'删除成功'});
    });
});



module.exports = router;
